<template>
  <el-dialog 
    :title="dialogTitle" 
    :visible.sync="dialogVisible" 
    width="900px"
    :append-to-body="true"
    @close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库编码" prop="stoCode">
            <el-input v-model="form.stoCode" placeholder="请输入仓库编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库名称" prop="stoName">
            <el-input v-model="form.stoName" placeholder="请输入仓库名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库类型" prop="stoTypeName">
            <el-select 
              v-model="form.stoTypeName" 
              placeholder="请选择仓库类型" 
              style="width: 100%;"
              @change="handleTypeChange"
            >
              <el-option 
                v-for="type in warehouseTypeList" 
                :key="type.id"
                :label="type.typeName" 
                :value="type.typeName"
              >
                <span style="float: left">{{ type.typeName }}</span>
                <img 
                  v-if="type.iconPath" 
                  :src="getIconUrl(type.iconPath)" 
                  style="float: right; width: 20px; height: 20px; margin-top: 2px;"
                />
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库状态" prop="enableState">
            <el-select v-model="form.enableState" placeholder="请选择状态" style="width: 100%;">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="仓库地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入仓库地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="面积(㎡)" prop="area">
            <el-input v-model="form.area" placeholder="请输入面积" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="容量(m³)" prop="capacity">
            <el-input v-model="form.capacity" placeholder="请输入容量" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="仓库图标">
            <div class="icon-preview-box">
              <img v-if="form.picPath" :src="getIconUrl(form.picPath)" alt="仓库图标" />
              <i v-else class="el-icon-picture-outline"></i>
              <span class="tip">图标会根据选择的仓库类型自动显示</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="form.remark" 
              type="textarea" 
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { wareAdd, update } from "@/api/index/yxl";
import { getAllWarehouseTypes } from "@/api/index/warehouseType";

export default {
  name: "WarehouseDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogType: 'add',
      dialogVisible: false,
      submitLoading: false,
      warehouseTypeList: [],
      form: {
        id: null,
        stoCode: '',
        stoName: '',
        stoTypeName: '综合仓',
        enableState: '1',
        contactPerson: '',
        contactPhone: '',
        address: '',
        area: '',
        capacity: '',
        picPath: '',
        remark: ''
      },
      rules: {
        stoCode: [
          { required: true, message: '请输入仓库编码', trigger: 'blur' }
        ],
        stoName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' }
        ],
        stoTypeName: [
          { required: true, message: '请选择仓库类型', trigger: 'change' }
        ],
        enableState: [
          { required: true, message: '请选择仓库状态', trigger: 'change' }
        ],
        contactPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return this.dialogType === 'add' ? '新增仓库' : '编辑仓库';
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val;
    },
    dialogVisible(val) {
      this.$emit('update:visible', val);
    }
  },
  created() {
    this.getWarehouseTypeList();
  },
  methods: {
    // 将后端返回的相对路径转换为可访问的完整URL
    getIconUrl(path) {
      if (!path) return '';
      // 已经是完整URL
      if (/^https?:\/\//i.test(path)) return path;
      // 兼容以/开头或不以/开头的路径
      const base = process.env.VUE_APP_BASE_API || '';
      if (!base) return path;
      if (base.endsWith('/') && path.startsWith('/')) {
        return base + path.substring(1);
      }
      if (!base.endsWith('/') && !path.startsWith('/')) {
        return base + '/' + path;
      }
      return base + path;
    },
    // 获取仓库类型列表
    getWarehouseTypeList() {
      getAllWarehouseTypes().then(res => {
        this.warehouseTypeList = res.data || res.rows || [];
        // 初始值：若已有选择的类型，自动设置图标
        if (this.form.stoTypeName) {
          this.handleTypeChange(this.form.stoTypeName);
        } else if (this.warehouseTypeList.length) {
          // 若无选择，默认选第一个启用类型
          this.form.stoTypeName = this.warehouseTypeList[0].typeName;
          this.handleTypeChange(this.form.stoTypeName);
        }
      }).catch(() => {
        this.warehouseTypeList = [];
      });
    },
    
    // 仓库类型改变时，自动更新图标和类型ID
    handleTypeChange(typeName) {
      const selectedType = this.warehouseTypeList.find(t => t.typeName === typeName);
      // 直接记录原始icon路径，由模板通过getIconUrl转换
      this.form.picPath = selectedType && selectedType.iconPath ? selectedType.iconPath : '';
      // 设置仓库类型ID到picClassId字段（后端用于关联warehouse_type表）
      this.form.picClassId = selectedType ? selectedType.id : null;
    },
    openDialog(type, data) {
      this.dialogType = type;
      this.dialogVisible = true;
      
      console.log('打开对话框:', type, data);
      
      if (type === 'edit' && data) {
        // 编辑时保留原始数据结构
        this.form = {
          id: data.stoId,
          stoId: data.stoId,
          stoCode: data.stoCode,
          stoName: data.stoName,
          stoTypeName: data.picClassName || '综合仓',  // 使用picClassName作为类型名称
          picClassId: data.picClassId || null,  // 仓库类型ID
          enableState: String(data.enableState || '1'),
          contactPerson: data.contactPerson || '',
          contactPhone: data.contactPhone || '',
          address: data.address || '',
          area: data.area ? String(data.area) : '',
          capacity: data.capacity ? String(data.capacity) : '',
          picPath: data.picPath || '',
          remark: data.remark || ''
        };
        console.log('编辑表单数据:', this.form);
        // 编辑时根据已有类型刷新图标
        this.handleTypeChange(this.form.stoTypeName);
      } else {
        this.form = {
          id: null,
          stoCode: '',
          stoName: '',
          stoTypeName: '综合仓',
          enableState: '1',
          contactPerson: '',
          contactPhone: '',
          address: '',
          area: '',
          capacity: '',
          picPath: '',
          remark: ''
        };
        // 新增时如果类型列表已加载，立即根据默认类型设置图标
        this.handleTypeChange(this.form.stoTypeName);
      }
    },
    
    handleClose() {
      this.dialogVisible = false;
      this.$refs.formRef.resetFields();
    },
    
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          const apiMethod = this.dialogType === 'add' ? wareAdd : update;
          
          // 打印提交的数据
          console.log('提交的表单数据:', this.form);
          
          apiMethod(this.form).then(res => {
            console.log('提交成功响应:', res);
            this.$message.success(res.msg || '操作成功');
            this.submitLoading = false;
            this.dialogVisible = false;
            this.$emit('success');
          }).catch(err => {
            console.error('提交失败:', err);
            this.$message.error(err.msg || err.message || '操作失败');
            this.submitLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}

.icon-preview-box {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  
  img {
    width: 60px;
    height: 60px;
    object-fit: contain;
    border-radius: 4px;
    background: #fff;
    padding: 4px;
  }
  
  i {
    font-size: 48px;
    color: #c0c4cc;
  }
  
  .tip {
    font-size: 12px;
    color: #909399;
  }
}
</style>
